import tushare as ts
import pandas as pd

# 初始化pro接口
pro = ts.pro_api('46b616e295c8d31f5a4b22891744af6414252720e80988442438a089')

# 拉取数据
df = pro.daily(**{
    "ts_code": "",  # 可以指定特定股票代码，如 '000001.SZ'
    "trade_date": "",
    "start_date": "20250301",  # 确保日期范围足够大
    "end_date": "20250320",
    "offset": "",
    "limit": ""
}, fields=[
    "ts_code",
    "trade_date",
    "open",
    "high",
    "low",
    "close",
    "pre_close",
    "change",
    "pct_chg",
    "vol",
    "amount"
])

# 确保数据按股票代码和交易日期排序
df = df.sort_values(by=['ts_code', 'trade_date'])

# 计算MA5和MA10
df['ma5'] = df.groupby('ts_code')['close'].transform(lambda x: x.rolling(window=5).mean())
df['ma10'] = df.groupby('ts_code')['close'].transform(lambda x: x.rolling(window=10).mean())

# 打印前20行以检查MA计算
print(df[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']].head(20))

# 找出5日线上穿10日线的时刻
df['ma5_cross_ma10'] = (df['ma5'] > df['ma10']) & (df['ma5'].shift(1) <= df['ma10'].shift(1))

# 打印交叉条件检查
df['ma5_greater_than_ma10'] = df['ma5'] > df['ma10']
df['ma5_prev_less_than_ma10'] = df['ma5'].shift(1) <= df['ma10'].shift(1)
print(df[['ts_code', 'trade_date', 'ma5', 'ma10', 'ma5_greater_than_ma10', 'ma5_prev_less_than_ma10']].head(20))

# 提取出买点股票
buy_signals = df[df['ma5_cross_ma10']]

# 获取股票列表
buy_stock_list = buy_signals[['ts_code', 'trade_date']].drop_duplicates().sort_values(by=['ts_code', 'trade_date'])

# 打印买点股票列表
print(buy_stock_list)

# 将结果保存到CSV文件
buy_stock_list.to_csv('buy_signals.csv', index=False)